package com.worldtvs.online.view;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.bzydroid.network.http.NetworkResponse;
import com.bzydroid.network.http.client.BzydroidHttpClient;
import com.bzydroid.network.http.exception.BzydroidNetworkExeception;
import com.bzydroid.network.http.response.HttpJSONObjectResponse;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.worldtv.lives.R;
import com.worldtvs.online.E4KidsConfig;
import com.worldtvs.online.E4KidsSlidingMenuActivity;
import com.worldtvs.online.adapter.ItemVideoRelativeAdapterPlay;
import com.worldtvs.online.customize.BaseRequestHandler;
import com.worldtvs.online.entity.InfoVideo;
import com.worldtvs.online.service.RequestService;
import com.worldtvs.online.util.Debug;
import com.worldtvs.online.util.Util;

public class SearchResultActivity extends E4KidsSlidingMenuActivity implements
	OnClickListener {
    private ListView lvVideo;
    private LinearLayout llLoading;
    private ItemVideoRelativeAdapterPlay adapter;

    private boolean isLoading;
    private RequestVideoNew requestVideoNew;

    private int page = 1;

    private ImageView ivABCancelSearch;
    private ImageView ivABSearch;
    private EditText edtABSearch;
    private LinearLayout llContainEdt;
    private ImageView tvABTitle;
    private LinearLayout llLoadingFooter;

    private String keyword;
    private TextView tvNoData;
    private ImageView ivABLogo;
    private AdView adView;
	private InterstitialAd interstitial;
	RelativeLayout rlContainAds;

    @Override
    public void onCreate(Bundle arg0) {
	super.onCreate(arg0);
	this.setContentView(R.layout.activity_list_relative);
	this.setBehindContentView(R.layout.frame_layout_container);
	// this.getSlidingMenu().setSecondaryMenu(R.layout.frame_right_container);
	this.setDefaultBar();
	configLeftSlideMenu();
	this.removeSlidingMenu();

	init();
    }

    private void init() {
	if (getIntent().getExtras() != null) {
	    keyword = getIntent().getExtras().getString(
		    E4KidsConfig.KEY_INTENT_SEARCH);
	}

	ivABCancelSearch = actionBar.getIvABCancelSearch();
	ivABSearch = actionBar.getIvABSearch();
	edtABSearch = actionBar.getEdtABSearch();
	llContainEdt = actionBar.getLlContainEdt();
	ivABLogo = actionBar.getIvABLogo();
	tvABTitle = actionBar.getIvTitle();

	ivABLogo.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View arg0) {
//		onBackPressed();
	    }
	});

	// edtABSearch.setOnEditorActionListener(searchAction);
	ivABSearch.setOnClickListener(this);
	ivABCancelSearch.setOnClickListener(this);

	edtABSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
	edtABSearch.setOnEditorActionListener(new OnEditorActionListener() {

	    @Override
	    public boolean onEditorAction(TextView arg0, int actionID,
		    KeyEvent arg2) {
		keyword = edtABSearch.getText().toString().trim();
		if (!keyword.equals("") || !TextUtils.isEmpty(keyword)) {
		    // check word sex
		    if (keyword.contains("sex") || keyword.contains("porn")
			    || keyword.contains("xxx")
			    || keyword.contains("sexy")
			    || keyword.contains("fuck")
			    || keyword.contains("shit")
			    || keyword.contains("naked")) {
			Toast.makeText(SearchResultActivity.this,
				"Keyword incorrect regulations !!!",
				Toast.LENGTH_SHORT).show();
		    } else {

			tvNoData.setVisibility(View.GONE);
			llLoading.setVisibility(View.VISIBLE);
			lvVideo.setVisibility(View.GONE);
//			adapter = new ItemVideoRelativeAdapterPlay(
//				SearchResultActivity.this, imageLoader, options);
			page = 1;
			loadMore();

			lvVideo.setAdapter(adapter);

		    }
		}
		return true;
	    }
	});

	rlContainAds = (RelativeLayout)findViewById(R.id.rlContainAds);
	interstitial = new InterstitialAd(getBaseContext());
	interstitial.setAdUnitId(getString(R.string.admod));
	 adView = (AdView) this.findViewById(R.id.ad);
	AdRequest adRequest = new AdRequest.Builder()
	 .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
	 .addTestDevice("")
			.build();
	adView.loadAd(adRequest);
	interstitial.loadAd(adRequest);
	interstitial.setAdListener(new AdListener() {
		@Override
		public void onAdLoaded() {
			
		}
	});
	lvVideo = (ListView) findViewById(R.id.lvRelative);

	tvNoData = (TextView) findViewById(R.id.tvNoData);

	LayoutInflater inflater = getLayoutInflater();
	View header = inflater.inflate(R.layout.layout_header, null);
	View footer = inflater.inflate(R.layout.layout_footer, null);
	llLoadingFooter = (LinearLayout) footer
		.findViewById(R.id.llLoadingFooter);
	lvVideo.addHeaderView(header);
	lvVideo.addFooterView(footer);

	llLoading = (LinearLayout) findViewById(R.id.ll_loading);

//	adapter = new ItemVideoRelativeAdapterPlay(SearchResultActivity.this,
//		imageLoader, options);

	// idCat = String.valueOf(application.getCatID());

	// if(idCat.equals("") || idCat.equals("0")|| idCat.equals("-1"))
	// {
	// idCat = "0";
	// }
	//
	// Debug.debug("CatId New Video : " + idCat);

	loadMore();
	lvVideo.setAdapter(adapter);

	// adapter.setClickItemVideo(new IClickItemVideo() {
	//
	// @Override
	// public void onclickItem(final String vid, final String linkvideo) {
	//
	// if (vid.equals("3") || vid.equals("10") || vid.equals("15")
	// || vid.equals("19")) {
	// if (app.isAds()) {
	// app.setAds(false);
	// MobileCore.init(self, E4KidsConfig.MO, LOG_TYPE.DEBUG);
	//
	// MobileCore.showOfferWall(self, new CallbackResponse() {
	// @Override
	// public void onConfirmation(TYPE arg0) {
	// Bundle bundle = new Bundle();
	// bundle.putString(E4KidsConfig.KEY_INTENT_VID,
	// vid);
	// bundle.putString(E4KidsConfig.KEY_INTENT_LINK,
	// linkvideo);
	//
	// goActivitySearch(SearchResultActivity.this,
	// PlayVideo.class, bundle);
	// }
	// });
	// } else {
	// Bundle bundle = new Bundle();
	// bundle.putString(E4KidsConfig.KEY_INTENT_VID, vid);
	// bundle.putString(E4KidsConfig.KEY_INTENT_LINK,
	// linkvideo);
	//
	// goActivitySearch(SearchResultActivity.this,
	// PlayVideo.class, bundle);
	// }
	// } else {
	// Bundle bundle = new Bundle();
	// bundle.putString(E4KidsConfig.KEY_INTENT_VID, vid);
	// bundle.putString(E4KidsConfig.KEY_INTENT_LINK, linkvideo);
	//
	// goActivitySearch(SearchResultActivity.this,
	// PlayVideo.class, bundle);
	// }
	//
	// }
	// });

	lvVideo.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
		    long arg3) {
		InfoVideo infoVideo = adapter.getItem(arg2);
		if (infoVideo != null) {
		    Bundle bundle = new Bundle();

		    bundle.putString(E4KidsConfig.KEY_INTENT_VID,
			    infoVideo.getVid());
		    bundle.putString(E4KidsConfig.KEY_INTENT_LINK,
			    infoVideo.getvYoutube());

		    goActivitySearch(SearchResultActivity.this,
			    PlayVideoYoutbe.class, bundle);
		}

	    }
	});

	lvVideo.setOnScrollListener(new OnScrollListener() {

	    @Override
	    public void onScrollStateChanged(AbsListView arg0, int arg1) {

	    }

	    @Override
	    public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
		if ((arg1 + arg2) == arg3 && isLoading) {
		    if (page <= 5) {
			isLoading = false;
			page = page + 1;
			llLoadingFooter.setVisibility(View.VISIBLE);

			loadMore();

			Debug.debug("Page New: " + page);
		    }
		}
	    }
	});
    }

    private class RequestVideoNew extends BaseRequestHandler {
	public RequestVideoNew(Activity context, OnClickListener clickTry) {
	    super(context, clickTry);
	}

	@Override
	public void onWait(BzydroidHttpClient arg0) {
	    super.onWait(arg0);
	    // llLoading.setVisibility(View.VISIBLE);
	}

	@Override
	public void onStarted(BzydroidHttpClient arg0) {
	    super.onStarted(arg0);
	    Debug.debug("onStarted");
	}

	@Override
	public void onSuccess(BzydroidHttpClient arg0, NetworkResponse arg1) {

	    // Debug.debug("Danh sach : " + a);
	    HttpJSONObjectResponse jsonObjectResponse = (HttpJSONObjectResponse) arg0
		    .getResponse();
	    try {
		JSONObject object = jsonObjectResponse.toJSONObject();
		//
		Debug.debug("Danh sach : " + object.toString());

		JSONObject jObjData = object
			.getJSONObject(E4KidsConfig.KEY_DATA);

		int code = jObjData.getInt(E4KidsConfig.KEY_CODE);

		if (code == 1) {
		    Debug.debug("Con du lieu");

		    isLoading = true;

		    JSONArray jArrVideo = jObjData
			    .getJSONArray(E4KidsConfig.Search.KEY_VIDEO);

		    int length = jArrVideo.length();

		    for (int i = 0; i < length; i++) {
			JSONObject jObj = jArrVideo.getJSONObject(i);

			InfoVideo infoVideo = parseJsonSearch(jObj);

			adapter.addData(infoVideo);
		    }
		    lvVideo.setVisibility(View.VISIBLE);
		} else {
		    Debug.debug("Het du lieu");
		    isLoading = false;
		    if (adapter.getCount() <= 0) {
			tvNoData.setVisibility(View.VISIBLE);
			lvVideo.setVisibility(View.GONE);
			llLoadingFooter.setVisibility(View.GONE);
		    } else {
			llLoadingFooter.setVisibility(View.GONE);
			tvNoData.setVisibility(View.GONE);
		    }
		}
	    } catch (JSONException e) {
		e.printStackTrace();
	    }
	}

	@Override
	public void onError(BzydroidHttpClient arg0,
		BzydroidNetworkExeception arg1) {
	    super.onError(arg0, arg1);
	    Debug.debug("onError");

	    if (!Util.isConnectingToInternet(SearchResultActivity.this)) {
		lvVideo.setVisibility(View.GONE);
		if (llLoading.getVisibility() == View.VISIBLE) {
		    llLoading.setVisibility(View.GONE);
		}
	    } else {
		lvVideo.setVisibility(View.VISIBLE);
	    }
	}

	@Override
	public void onFinished(BzydroidHttpClient arg0) {
	    super.onFinished(arg0);
	    Debug.debug("onFinished");
	    llLoading.setVisibility(View.GONE);
	    llLoadingFooter.setVisibility(View.GONE);
	}
    }

    private void loadMore() {
	if (requestVideoNew == null) {
	    requestVideoNew = new RequestVideoNew(SearchResultActivity.this,
		    clickTry);
	}
	RequestService.rqSearch(keyword, String.valueOf(page), packageName,
		requestVideoNew);

    }

    private OnClickListener clickTry = new OnClickListener() {

	@Override
	public void onClick(View v) {
	    Debug.debug("clickTry Page : " + page);

	    loadMore();
	}
    };

    @Override
    public void onClick(View arg0) {
	switch (arg0.getId()) {
	case R.id.iv_search:
	    if (llContainEdt.getVisibility() == View.GONE) {
		llContainEdt.setVisibility(View.VISIBLE);
		ivABSearch.setVisibility(View.GONE);
		tvABTitle.setVisibility(View.GONE);
		edtABSearch.setFocusable(true);
		edtABSearch.requestFocus();
		showBoard(edtABSearch);
	    }
	    break;
	case R.id.iv_cancel:
	    String text = edtABSearch.getText().toString().trim();
	    if (!text.equals("")) {
		edtABSearch.setText("");
	    } else {
		llContainEdt.setVisibility(View.GONE);
		ivABSearch.setVisibility(View.VISIBLE);
		tvABTitle.setVisibility(View.VISIBLE);
		edtABSearch.setFocusable(true);
		hiddenBoard(edtABSearch);
	    }
	    break;
	}
    }

}
